//
//  GTLoginController.swift
//  swiftWEIbo
//
//  Created by mac－gt on 15/11/24.
//  Copyright © 2015年 mac－gt. All rights reserved.
//

import UIKit
import SVProgressHUD
class GTLoginController: UIViewController {
   //让webView成为当前控制器的View
    override func loadView() {
        view=webView
        webView.delegate=self
    }
    override func viewDidLoad() {
        super.viewDidLoad()

       view.backgroundColor=UIColor.whiteColor()
        navigationItem.leftBarButtonItem=UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "fillBtnClick")
        navigationItem.rightBarButtonItem=UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "canleClick")
        //加载登陆页面
        let request=NSURLRequest(URL: GTNetworking.sharedInsatance.loadUrl())
        webView.loadRequest(request)
    }
    //取消按钮
    func canleClick(){
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    // 填充按钮
    func fillBtnClick(){
        let jsCode="document.getElementById('userId').value='18317957950';" + "document.getElementById('passwd').value='yueyue920407l..';"
        webView .stringByEvaluatingJavaScriptFromString(jsCode)
    }
    lazy var webView: UIWebView = UIWebView()
}
// 扩展      代理
extension GTLoginController:UIWebViewDelegate{
    // webView开始加载调用
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD .showWithStatus("正在加载中...", maskType: SVProgressHUDMaskType.Black)
    }
    //webView加载完调用
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    // 家在一个连接的时候调用  在这类可以拦截加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       let urlString = request.URL?.absoluteString
        if !urlString!.hasPrefix(GTNetworking.sharedInsatance.redirect_uri){
            return true
        }
        if let query=request.URL?.query{
            let codeStr="code="
            if query.hasPrefix(codeStr){
                let queryStr=query as NSString
             let code=queryStr.substringFromIndex(codeStr.characters.count)
                loadAccessToken(code)
            }
        }
        return false
    }
    // 加载 AccessToken
    func loadAccessToken(code:String){
      GTNetworking.sharedInsatance.loadAccessToken(code) { (resut,error) -> () in
       
        if resut==nil || error != nil{
             SVProgressHUD.showErrorWithStatus("授权失败")
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.canleClick()

            })
            return
          
        }
        let ats = GTAcounts(dict: resut!)
        ats.saveAccount()
        ats.loadUserInfo({ (error) -> () in
            if error != nil{
                self.netError("加载用户出错")
                return
            }
          
            self.canleClick()
            (UIApplication .sharedApplication().delegate as! AppDelegate).switchRootController(false)
        })
        }
        
        
    }
    private func netError(message: String) {
        SVProgressHUD.showErrorWithStatus(message, maskType: SVProgressHUDMaskType.Black)

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            self.canleClick()
        })
    }

}